#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <fcntl.h>
#include <cstdio>
#include <cstring>
#include <cstdarg>

enum
{
    Debug = 0,
    Info,
    Warning,
    Error,
    Fatal
};

enum
{
    Screen = 10,
    OneFile,
    ClassFile
};

const std::string LevelToString(int level)
{
    switch (level)
    {
    case Debug:
        return "Debug";
    case Info:
        return "Info";
    case Warning:
        return "Warning";
    case Error:
        return "Error";
    case Fatal:
        return "Fatal";
    default:
        break;
    }
}

const int defautstyle = Screen;
const std::string default_filename = "log.";
const std::string logdir = "log";

class Log
{
public:
    Log()
    :_style(Screen), _filename(default_filename)
    {
        mkdir(logdir.c_str(), 0775);
    }

    void Enable(int sty)
    {
        _style = sty;
    }

    std::string TimeStampExLocalTime()
    {
        time_t currtime = time(nullptr);
        struct tm * curr = localtime(&currtime);
        char time_buff[1024];
        memset(time_buff, 0, sizeof(time_buff));
        snprintf(time_buff, sizeof(time_buff), "%d-%d-%d %d:%d:%d", 
        curr->tm_year + 1900, curr->tm_mon + 1, curr->tm_mday, curr->tm_hour, curr->tm_min, curr->tm_sec);

        return time_buff;
    }

    void writeLogToClassFile(std::string filename, const std::string& message)
    {
        filename = default_filename + filename;
        int fd = open(filename.c_str(), O_CREAT | O_APPEND | O_WRONLY, 666);
        if(fd < 0)
        {
            perror("open");
            exit(-1);
        }

        write(fd, message.c_str(), message.size());
        close(fd);
    }

    void WriteLogToClassFile(const std::string& levelstr, const std::string& message)
    {
        std::string filename = logdir + "/" + default_filename + levelstr;
        writeLogToClassFile(filename, message);
    }

    void writeLog(int levelstr, const std::string message)
    {
        switch(levelstr)
        {
            case Screen:
                std::cout << message << std::endl;
            break;
            case OneFile:
                writeLogToClassFile("all", message);
            break;
            case ClassFile:
            
            break;
            default:

            break;
        }
    }
    
    void LogMessage(int level, const char *format, ...)
    {
        std::string leftbuff;
        leftbuff +="[" + LevelToString(level) + "]";
        leftbuff += "[" + TimeStampExLocalTime() + ']';
        leftbuff += '[' + std::to_string(getpid()) + ']';

        va_list args;
        va_start(args, format);
        char rightbuff[1024];
        memset(rightbuff, 0, sizeof(rightbuff));
        vsnprintf(rightbuff, sizeof(rightbuff), format, args);
        va_end(args);

        writeLog(level, leftbuff + rightbuff);
    }

private:
    int _style;
    std::string _filename;
};